﻿using STHPMS1.Common.C_Entity;
using STHPMS1.Common.C_Entity.Stmpms1;
using STHPMS1.ICore;
using STHPMS1.ICore.I_Core;
using STHPMS1.ICore.I_UI;
using STHPMS1.Web.W_Model.EnumModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Data;
using System.Reflection;
using System.IO;

namespace STHPMS1.Web.W_Controller
{
    [RoutePrefix("api/roadway")]
    public class B_RoadwayPage1Controller : STHPMS1.Web.W_Core.MyController
    {
        [Route("")]
        [Route("page/{page?}", Name = "GetroadwayByPage")]
        [Route("rows/{rows?}")]
        [Route("page/{page?}/rows/{rows?}")]
        public IHttpActionResult Get(int? region = null, int? direction = null, DateTime? checkDate=null, int page = 1,  int rows = 10)
        {
            int p = page;
            int s = rows;

            PagingInfo info = new PagingInfo();
            info.PageIndex = p> 0 ? p - 1 : 0;
            info.PageSize = s;
            info.TotalRecords = 0;

            var data=this.Scene.Bll.B_Roadway.Get<B_Roadway>(null, info).ToArray();
            if(data==null) return NotFound();

            var result = new { rows = data, total = info.TotalRecords };

            return Ok(result);
        }

        [Route("")]
        public HttpResponseMessage Post(B_Roadway entity)
        {
            this.Scene.Bll.B_Roadway.Save(entity);

            var response = Request.CreateResponse(HttpStatusCode.Created);
            string uri = Url.Link("GetroadwayByPage", new { page = 1 });
            response.Headers.Location = new Uri(uri);

            return response;
        }

        [Route("")]
        public void Delete(B_Roadway entity)
        {
            this.Scene.Bll.B_Roadway.Remove(entity);
        }

        /// <summary>
        /// 获取所有路线的id与名称字典 
        /// </summary>
        /// <returns></returns>
        [Route("dict")]
        public dynamic GetDict()
        {
            var innerJoinQuery =
                from road in this.Scene.Bll.B_Roadway.Dicts()
                select new { id = road.Key, text = road.Value };
            return innerJoinQuery;
        }

        /// <summary>
        /// 获取所有道路信息
        /// </summary>
        /// <returns></returns>
        [Route("all")]
        public dynamic GetAllRoads()
        {
            return this.Scene.Bll.B_Roadway.GetAll<B_Roadway>().ToArray();
        }

        

        /// <summary>
        /// 上传数据处理
        /// </summary>
        /// <param name="file">文件路径</param>
        /// <returns></returns>
        [Route("saveFile")]
        public HttpResponseMessage PostSaveFile(string file)
        {

            DataTable entity = null;//实体数据
            Excel_BaseImportData exData = null;//导入数据
            if (File.Exists(file))
            {
                try
                {
                    int startRow = 0;//Excel列头位置

                    DataTable dt = Common.C_Excel.ExcelTool.RenderDataTableFromExcel(file, startRow);//获取Excel的DataTable
                    //验证Excel表头格式?
                    entity = GetData(dt,startRow);//将要导入的实体Table
                    exData = new Excel_BaseImportData(new B_Roadway());//弯沉实体
                    exData.DtSource = entity;
                    exData.TableName = "B_Roadway"; //弯沉
                    this.Scene.Bll.Excel.ImportData(exData);

                }
                catch (Exception ex)
                {
                    File.Delete(file);//删除上传数据
                    //抛出错误
                    var response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
                    {
                        Content = new StringContent(ex.Message),
                        ReasonPhrase = "Server Error"
                    };
                    throw new HttpResponseException(response);
                }
            }
            else
            {
                //抛出错误
                var response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content = new StringContent("服务器未能保存上传文件，请联系管理员"),
                    ReasonPhrase = "Server Error"
                };
                throw new HttpResponseException(response);
            }
            var res = Request.CreateResponse(HttpStatusCode.Created);
            // Generate a link to the new book and set the Location header in the response.
            string uri = Url.Link("GetroadwayByPage", new { page = 1 });
            res.Headers.Location = new Uri(uri);

            return res;
        }

        /// <summary>
        /// 反射获取对象的所有属性
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        private PropertyInfo[] GetAllProperty(object t)
        {
            Type temp = t.GetType();
            return temp.GetProperties();
        }
        /// <summary>
        /// 获取路线实体的DataTable
        /// </summary>
        /// <param name="excel">导入excel</param>
        /// <param name="startRow">表头位置</param>
        /// <returns></returns>
        private DataTable GetData(DataTable excel, int startRow)
        {
            List<string> rdIds = new List<string>();//路线变化
            Dictionary<string, string> admsDic = new Dictionary<string, string>();//Excel的行政区域
            DataTable kh = new DataTable();
            PropertyInfo[] propertys = GetAllProperty(new B_Roadway());
            foreach (PropertyInfo p in propertys)
            {
                kh.Columns.Add(new DataColumn(p.Name.ToUpper()));
            }
            kh.Columns.Add(new DataColumn("index")); //记录错误行号
            if (excel.Rows.Count == 0)
            {
                throw new Exception("Excel没有数据");
            }
            int index = startRow + 1;
            foreach (DataRow r in excel.Rows)
            {
               
                string _RDWAYID = r[0].ToString();//路线编号
                double _version = this.Scene.Bll.B_Roadway.GetNewHistoryVersion(_RDWAYID, true);//版本号
                if(rdIds.Count > 0 && rdIds.Contains(_RDWAYID))
                {
                    throw new Exception("Excel第"+ index+"行的路线编号"+ _RDWAYID+"存在重复");
                }
                else
                {                    
                    rdIds.Add(_RDWAYID);
                }
                //判断是否在数据库中已经重复
                if (this.Scene.Bll.B_Roadway.Exists(_RDWAYID))
                {
                    throw new Exception("第" + index + "行的路线编号" + _RDWAYID + "已经存在");
                }
                string _NAME = r[1].ToString();//路线名称
                
                string _BEGINMP = r[2].ToString();//起点桩号
                string _ENDMP = r[3].ToString();//结束桩号
               
                string _ADMGRD = r[4].ToString().Trim();//行政等级
                int _ADMGRDId = -1;
                foreach(ICore.I_Entity.Info.IComboxJsonInfo f in this.Scene.Data.AdminLevelEnum)
                {
                    if(f.text == _ADMGRD)
                    {
                        _ADMGRDId = f.id;
                    }
                }
                if (_ADMGRDId == -1)
                {
                    throw new Exception("系统没有找到对应的行政等级,请检查第" + index + "行");
                }

                string _STRUCTURES = r[5].ToString();//构造物

                string _IMPORTDATE = DateTime.Now.ToShortDateString();
                DataRow dr = kh.NewRow();

                dr["RDWAYID"] = _RDWAYID;
                dr["NAME"] = _NAME;
                dr["BEGINMP"]= _BEGINMP;
               dr["ENDMP"]= _ENDMP;
                dr["ADMGRD"]= _ADMGRDId;
                dr["STRUCTURES"]=_STRUCTURES ;
                dr["IMPORTDATE"] = _IMPORTDATE;
                dr["HIS_VERSION"] = _version;
                dr["index"] = index++;
                kh.Rows.Add(dr);

            }
            return kh;
        }

        /// <summary>
        /// 上传返回上传后路径
        /// </summary>
        [Route("uploadFile")]
        public void PostUploadFile()
        {

            System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;
            string uploadPath =
              System.Web.HttpContext.Current.Server.MapPath("~/App_Data/Upload") + "\\";
            string PhysicalPath = "";
            if (hfc.Count > 0)
            {
                if (!Directory.Exists(uploadPath))
                {
                    Directory.CreateDirectory(uploadPath);
                }
                PhysicalPath = uploadPath + hfc[0].FileName;
                hfc[0].SaveAs(PhysicalPath);
            }

            System.Web.HttpContext.Current.Response.Write(PhysicalPath);
            System.Web.HttpContext.Current.Response.End();
        }
    }
}